package com.app.android.coliy.ui.fragment;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.android.coliy.R;
import com.app.android.coliy.adapter.DeviceAdapter;
import com.app.android.coliy.dialog.SendTest_Dialog;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.manager.BuildPackgeManager;
import com.app.android.coliy.tool.CommLoading;
import com.app.android.coliy.tool.Log;
import com.app.android.coliy.ui.view.Comm_SubmitBtnView;
import com.app.android.coliy.ui.view.RoundProgressBar;
import com.app.android.coliy.util.ToastUtil;
import com.feasycom.bean.BluetoothDeviceWrapper;
import com.feasycom.controler.FscBleCentralApi;
import com.feasycom.controler.FscBleCentralApiImp;
import com.feasycom.controler.FscBleCentralCallbacksImp;
import com.lzy.okgo.utils.HttpUtils;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by Administrator on 2018/8/20.
 */

public class BlueToothListFragment extends BaseFragment {

    public static boolean isConnected = false;

    private Context mContext;
    private BluetoothDeviceWrapper currentDeviceWrapper;

    private View rootView;
    private ImageView iv_scan;
    private DeviceAdapter mAdapter;
    private RoundProgressBar roundprogressbar;
    private LinearLayout ll_divice_info, ll_unconnect, ll_disconnect;
    private RelativeLayout rl_connected;
    private Comm_SubmitBtnView csb_print;
    private ProgressBar pb_blue, pb_red, pb_yellow;
    private TextView tv_blue, tv_red, tv_yellow, tv_text, t_test, tv_tantou, tv_value1, tv_unit1, tv_value2, tv_unit2, tv_value_title1, tv_value_title2;
    LinearLayout ll_value1, ll_value2;

    Vibrator vibrator;
    Ringtone ringtone = null;
    long[] VIBRATION_PATTERN = new long[]{0, 180, 80, 120};

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_bluetoothlist, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initBluethooth();
        refreshState();
    }

    private void initView() {
        iv_scan = rootView.findViewById(R.id.iv_scan);

        RecyclerView recyclerview = rootView.findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new DeviceAdapter();
        recyclerview.setAdapter(mAdapter);

        roundprogressbar = rootView.findViewById(R.id.roundprogressbar);
        ll_divice_info = rootView.findViewById(R.id.ll_divice_info);
        rl_connected = rootView.findViewById(R.id.rl_connected);
        ll_unconnect = rootView.findViewById(R.id.ll_unconnect);
        ll_disconnect = rootView.findViewById(R.id.ll_disconnect);
        csb_print = rootView.findViewById(R.id.csb_print);
        pb_blue = rootView.findViewById(R.id.pb_blue);
        pb_red = rootView.findViewById(R.id.pb_red);
        pb_yellow = rootView.findViewById(R.id.pb_yellow);
        tv_blue = rootView.findViewById(R.id.tv_blue);
        tv_red = rootView.findViewById(R.id.tv_red);
        tv_yellow = rootView.findViewById(R.id.tv_yellow);
        tv_text = rootView.findViewById(R.id.tv_text);
        t_test = rootView.findViewById(R.id.t_test);
        tv_tantou = rootView.findViewById(R.id.tv_tantou);
        tv_value1 = rootView.findViewById(R.id.tv_value1);
        tv_unit1 = rootView.findViewById(R.id.tv_unit1);
        ll_value1 = rootView.findViewById(R.id.ll_value1);
        tv_value2 = rootView.findViewById(R.id.tv_value2);
        tv_unit2 = rootView.findViewById(R.id.tv_unit2);
        ll_value2 = rootView.findViewById(R.id.ll_value2);
        tv_value_title1 = rootView.findViewById(R.id.tv_value_title1);
        tv_value_title2 = rootView.findViewById(R.id.tv_value_title2);

        iv_scan.setOnClickListener(this);
        ll_disconnect.setOnClickListener(this);
        csb_print.setOnClickListener(this);
        t_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                byte[] bytes = {1, 3, 0, 0, 10, -14, 3, 10, -41, 35, 61, 10, -41, 35, 35, -82, 4};
                parsePacket(bytes);
            }
        });
        //点击设备列表，选择一个设备连接
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            currentDeviceWrapper = (BluetoothDeviceWrapper) adapter.getItem(position);
            try {
                connectionBlueTooth();
            } catch (Exception e) {
                e.printStackTrace();
            }

//            Intent intent = new Intent(mContext, SendDataActivity.class);
//            intent.putExtra("device",currentDeviceWrapper);
//            startActivity(intent);

        });
    }

    FscBleCentralApi fscBleCentralApi;

    private Timer timerUI;
    private TimerTask taskUI;
    private static String[] PERMISSIONS_LOCATION = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.BLUETOOTH_PRIVILEGED
    };
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.BLUETOOTH_PRIVILEGED
    };
    private final int REQUEST_LOCATION = 3;
    private final int REQUEST_FILE = 4;

    private void initBluethooth() {
        if (fscBleCentralApi == null) {
            fscBleCentralApi = FscBleCentralApiImp.getInstance(mContext);
            fscBleCentralApi.initialize();
            fscBleCentralApi.setCallbacks(new FscBleCentralCallbacksImp() {
                @Override
                public void startScan() {
                    HttpUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("收到开始扫描事件");
                            startRefresh();
                        }
                    });
                }

                @Override
                public void stopScan() {
                    HttpUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("收到结束扫描事件");
                            stopRefresh();
                        }
                    });
                }

                //发现设备
                @Override
                public void blePeripheralFound(BluetoothDeviceWrapper device, int rssi, byte[] record) {
                    Log.i("发现设备");
                    if (!TextUtils.isEmpty(device.getName())) {
                        if (device.getRssi() > -100 && device.getRssi() < 0) {
                            boolean deviceInAdapter = false;
                            for (BluetoothDeviceWrapper model : mAdapter.getData()) {
                                if (device.getAddress().equals(model.getAddress())) {
                                    deviceInAdapter = true;
                                    break;
                                }
                            }
                            if (!deviceInAdapter) {
//                            mAdapter.addData(device);
                                HttpUtils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mAdapter.addData(device);
                                    }
                                });
                            }
                        }
                    }
                }

                //收到数据包
                @Override
                public void packetReceived(BluetoothGatt gatt, BluetoothDevice device, BluetoothGattService service, BluetoothGattCharacteristic ch, String strValue, String hexString, byte[] rawValue, String timestamp) {
                    super.packetReceived(gatt, device, service, ch, strValue, hexString, rawValue, timestamp);
                    if (rawValue.length == 13 || rawValue.length == 17) {
                        HttpUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                parsePacket(rawValue);
                            }
                        });
                    }
                }

                //连接成功
                @Override
                public void blePeripheralConnected(BluetoothGatt gatt, BluetoothDevice device) {
                    super.blePeripheralConnected(gatt, device);
                    Log.i("连接成功");
                    HttpUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showSuccess(mContext, "连接成功");
                            refreshState();
                            CommLoading.dismissLoading();
                        }
                    });
                }

                //断开连接
                @Override
                public void blePeripheralDisonnected(BluetoothGatt gatt, BluetoothDevice device) {
                    super.blePeripheralDisonnected(gatt, device);
                    Log.i("断开连接");
                    HttpUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            CommLoading.dismissLoading();
                            currentDeviceWrapper = null;
                            ToastUtil.showWarning(mContext, "断开连接");
                            refreshState();
                        }
                    });
                }

                //发数据进度回调
                @Override
                public void sendPacketProgress(BluetoothGatt gatt, BluetoothDevice device, BluetoothGattCharacteristic ch, int percentage, byte[] sendByte) {
                    super.sendPacketProgress(gatt, device, ch, percentage, sendByte);
                    Log.i("发数据进度回调：" + percentage + "%");
                    HttpUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                        tv_text.setText(tv_text.getText() + "" + percentage);
                            if (sendTest_dialog != null) {
                                if (percentage <= 100) {
                                    sendTest_dialog.setProgress(percentage);
                                } else if (percentage == 100) {
//                        new Handler().postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                hidePrintLoadingDialog();
//                            }
//                        }, 500);
                                    hidePrintLoadingDialog();
                                }
                            }
                        }
                    });
                }
            });
//            int permissionLocation = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION);
//            int permissionFile = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE);
//            if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_LOCATION, REQUEST_LOCATION);
//            } else if (permissionFile != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_FILE);
//            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (rootView != null) {
            checkPermis();
        }
    }

    private void checkPermis()
    {
        Acp.getInstance(mContext).request(new AcpOptions.Builder()
                        .setPermissions(Manifest.permission.ACCESS_FINE_LOCATION
                                , Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                                , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .setDeniedMessage(getResources().getString(R.string.denied_message))
                        .setDeniedCloseBtn(getResources().getString(R.string.denied_close))
                        .setDeniedSettingBtn(getResources().getString(R.string.denied_setting))
                        .setRationalMessage(getResources().getString(R.string.rational_message))
                        .setRationalBtn(getResources().getString(R.string.rational_btn))
                        .build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        Log.i( "onGranted: 同意授权" );
                        startScanBlueTooth();
                        refreshState();
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        Log.i("onDenied: 拒绝权限" );
                    }
                });
    }

    //解析数据
    private void parsePacket(byte[] bytes) {
        //低  高  01 03 00 00    06   02 03   CD CC 4C 3E    9A 76
        //06  数据长度
        //02  低八位：   低4位:  单位值     高4位 ： 是否产生报警
        //03  高八位:    探头类型
        int length = bytes[4];   //数据长度
        int tantou = (int) bytes[6];  //03   探头类型

        int high = getHeightFour(bytes[5]);         //高4位   是否产生报警
        int low = getLowFour(bytes[5]);             //低4位   单位值

        String tantouStr = "";
        String danweiStr = "";
        switch (tantou) {
            case 2:    // 02为表面污染     当探头类型为表面污染时 单位值 1为CPS   2为Bq/cm2
                tantouStr = "表面污染";
                if (low == 1) {  //CPS
                    danweiStr = "CPS";
                } else if (low == 2) {   //Bq/cm2
                    danweiStr = "Bq/cm²";
                }
                break;
            case 3:     //03 为CS30A      当探头类型为CS30A时  单位值 1为uGy/h  2为uSv/h
                tantouStr = "CS30A";
                if (low == 1) {     //uGy/h

                    danweiStr = "uGy/h";
                } else if (low == 2) {   //uSv/h
                    danweiStr = "uSv/h";
                }
                break;
        }

        tv_tantou.setText(tantouStr + "");
        //测量值1
        if (length >= 6) {
            byte[] byte1 = {bytes[7], bytes[8], bytes[9], bytes[10]};
            float value1 = getFloat(byte1);
            tv_value1.setText(value1 + "");
            tv_unit1.setText(danweiStr + "");
        }

        //测量值2
        if (length >= 10) {
            byte[] byte2 = {bytes[11], bytes[12], bytes[13], bytes[14]};
            float value2 = getFloat(byte2);
            tv_value2.setText(value2 + "");
            tv_unit2.setText(danweiStr + "");
        } else {

        }

        //两个值
        if (length >= 10) {
            tv_value_title1.setText("α:");
            tv_value_title2.setText("β:");
            ll_value1.setVisibility(View.VISIBLE);
            ll_value2.setVisibility(View.VISIBLE);
        } else {
            //一个值
            tv_value_title1.setText("Y:");
            ll_value1.setVisibility(View.VISIBLE);
            ll_value2.setVisibility(View.GONE);
        }

//        String str = "探头类型：" + tantou + "（" + tantouStr + "）   是否报警：" + high + "  单位值:" + low + "（" + danweiStr + "）  测量值:" + value;
//        Log.i("test", str);
//        tv_text.setText(tv_text.getText() + "\n" + str);

        if (high == 15) {
            //报警
            tv_value1.setTextColor(Color.parseColor("#F82518"));
            tv_unit1.setTextColor(Color.parseColor("#F82518"));
            tv_value2.setTextColor(Color.parseColor("#F82518"));
            tv_unit2.setTextColor(Color.parseColor("#F82518"));
            alarm();
        } else {
            tv_value1.setTextColor(Color.parseColor("#3469F8"));
            tv_unit1.setTextColor(Color.parseColor("#3469F8"));
            tv_value2.setTextColor(Color.parseColor("#3469F8"));
            tv_unit2.setTextColor(Color.parseColor("#3469F8"));
        }
    }

    private void alarm() {
        //震动
        vibrator.vibrate(VIBRATION_PATTERN, -1);
        //声音
        if (ringtone == null) {
            Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            ringtone = RingtoneManager.getRingtone(mContext, notificationUri);
            if (ringtone == null) {
                return;
            }
        }
        if (!ringtone.isPlaying()) {
            String vendor = Build.MANUFACTURER;
            ringtone.play();
            if (vendor != null && vendor.toLowerCase().contains("samsung")) {
                Thread ctlThread = new Thread() {
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            if (ringtone.isPlaying()) {
                                ringtone.stop();
                            }
                        } catch (Exception e) {
                        }
                    }
                };
                ctlThread.run();
            }
        }
    }

    //获取高四位
    public static int getHeightFour(byte data) {
        int heightfour;
        heightfour = ((data & 0xf0) >> 4);
        return heightfour;
    }

    //获取低四位
    public static int getLowFour(byte data) {
        int lowfour;
        lowfour = (data & 0x0f);
        return lowfour;
    }

    //字节转float
    public static float getFloat(byte[] b) {
        int accum = 0;
        accum = accum | (b[0] & 0xff) << 0;
        accum = accum | (b[1] & 0xff) << 8;
        accum = accum | (b[2] & 0xff) << 16;
        accum = accum | (b[3] & 0xff) << 24;
        return Float.intBitsToFloat(accum);
    }

    //刷新连接连接状态
    private void refreshState() {
        if (currentDeviceWrapper != null) {
            rl_connected.setVisibility(View.VISIBLE);
            ll_unconnect.setVisibility(View.GONE);
        } else {
            rl_connected.setVisibility(View.GONE);
            ll_unconnect.setVisibility(View.VISIBLE);
        }
        //是否连接
        isConnected = fscBleCentralApi.isConnected();

//        rl_connected.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != timerUI) {
            timerUI.cancel();
            timerUI = null;
        }
        if (null != taskUI) {
            taskUI.cancel();
            taskUI = null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        fscBleCentralApi.stopScan();
        if (null != timerUI) {
            timerUI.cancel();
            timerUI = null;
        }
        if (null != taskUI) {
            taskUI.cancel();
            taskUI = null;
        }
    }

    private final int ENABLE_BT_REQUEST_ID = 2;

    /**
     * 开始扫描
     */
    public void startScanBlueTooth() {
        Log.i("调用开始扫描");

        if (fscBleCentralApi.isBtEnabled() == false) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_ID);
        }
        if (!fscBleCentralApi.checkBleHardwareAvailable()) {
            com.feasycom.util.ToastUtil.show(mContext, "is not support ble");
        }
        fscBleCentralApi.startScan(5000);
    }

    /**
     * 连接蓝牙
     */
    public void connectionBlueTooth() {
        if (currentDeviceWrapper != null) {
            fscBleCentralApi.connect(currentDeviceWrapper.getAddress());
            CommLoading.showLoading(mContext, getString(R.string.bluetooth_connecting));
        }
    }

    /**
     * 断开连接
     */
    public void disConnectionBlueTooth() {
        try {
            if (fscBleCentralApi.isConnected()) {
                fscBleCentralApi.disconnect();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 写数据
     */
    BuildPackgeManager manager;
    Handler handler = new Handler();


    SendTest_Dialog sendTest_dialog;

    //显示文字输入弹窗
    private void showPrintLoadingDialog() {
        sendTest_dialog = new SendTest_Dialog(mContext);
        sendTest_dialog.setIntputCallBack(new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                String text = (String) obj;
                sendpacket(text);
            }
        });
        sendTest_dialog.show();
    }

    //发送数据
    private void sendpacket(String text) {
        try {
            byte[] data = text.getBytes("UTF-8");
            tv_text.setText(tv_text.getText() + "\n" + "发送数据:" + Arrays.toString(data) + "\n");
            Log.i("发数据包:" + Arrays.toString(data));
            if (fscBleCentralApi.isConnected()) {
                fscBleCentralApi.send(data);
            } else {
                ToastUtil.showWarning(mContext, getString(R.string.bluetooth_connect_tips));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭文字输入弹窗
    private void hidePrintLoadingDialog() {
//        if (sendTest_dialog != null) {
//            sendTest_dialog.dismiss();
//        }
    }

    //点击事件
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.iv_scan:              //开始扫描
                mAdapter.setNewData(null);
                startScanBlueTooth();
                break;
            case R.id.ll_disconnect:       //断开连接
                disConnectionBlueTooth();
                break;
            case R.id.csb_print:        //发送数据
                showPrintLoadingDialog();
                break;
        }
    }

    //开始旋转动画
    private void startRefresh() {
        if (iv_scan.getAnimation() == null) {
            RotateAnimation ta = new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
            ta.setDuration(500);
            ta.setInterpolator(new LinearInterpolator());
            ta.setRepeatCount(-1);
            iv_scan.startAnimation(ta);
        }
    }

    //结束旋转动画
    private void stopRefresh() {
        iv_scan.clearAnimation();
    }


}
